package com.putao.album.setting;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.album.ActivityAlbumPhotoSelect;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.ActivityChildManager;
import com.putao.album.child.crop.ActivityCropImage;
import com.putao.album.dialog.DialogBuilderFactory;
import com.putao.album.dialog.SelectDialogBuilder;
import com.putao.album.dialog.ShareAppDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.fileupload.FileUploadState;
import com.putao.album.share.ShareTools;
import com.putao.album.user.ActivityLoginRegister;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.AppHelper;
import com.putao.album.util.BitmapHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.SharedPreferencesHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/27.
 */
public class ActivitySettings extends BaseActivity {
    private TextView title_tv;
    private boolean mBoolWifiOnly, mBoolBackUpload;
    private Button btn_set_using_only_wifi, btn_set_backround_upload;
    private ShareTools mShareTools;
    private ImageView user_icon;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_settings;
    }

    @Override
    public void doInitSubViews(View view) {
        queryViewById(R.id.right_btn_ll).setVisibility(View.GONE);
        btn_set_using_only_wifi = queryViewById(R.id.btn_set_using_only_wifi, true);
        btn_set_backround_upload = queryViewById(R.id.btn_set_backround_upload, true);
        addOnClickListener(R.id.back_btn,
                R.id.set_layout_about_us,
                R.id.set_layout_account_security,
                R.id.set_layout_baby_manager,
                R.id.set_layout_lockpwd_set,
                R.id.set_layout_login_out,
                R.id.set_layout_opinion_feedback,
                R.id.set_layout_clear_cache,
                R.id.set_layout_user_icon,
                R.id.set_layout_shareto_friend);

        title_tv = queryViewById(R.id.title_tv);
        title_tv.setText(R.string.page_title_setting);

        user_icon = (ImageView) findViewById(R.id.user_icon);

        EventBus.getDefault().register(this);
    }

    @Override
    public void doInitData() {
        mBoolWifiOnly = SharedPreferencesHelper.readBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_UP_DOWN_ONLY_WIFI, true);
        mBoolBackUpload = SharedPreferencesHelper.readBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_COUNTINUTE_UPLOAD_BACKGROUND, true);

        mShareTools = new ShareTools(this);
        updateOnOffBtnBackground(btn_set_using_only_wifi, mBoolWifiOnly);

        updateOnOffBtnBackground(btn_set_backround_upload, mBoolBackUpload);

        getUserAvatar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_UPLOAD_PHOTOS:
                Bundle bundle = event.bundle;
                String status = bundle.getString("status");
                if (FileUploadState.START.equals(status)) {
                    mActivity.finish();
                }
                break;
            case PuTaoConstants.EVENTBUS_FINISH_PHOTO_SELECT:
                photo_path = event.bundle.getString("photo_path");
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .considerExifParams(true)
                        .build();
                ImageLoader.getInstance().displayImage("file://" + photo_path, user_icon, options);
                getUploadToken();
                break;
        }
    }

    private void updateOnOffBtnBackground(View view, boolean on) {
        if (on) {
            view.setBackgroundResource(R.drawable.set_button_on);
        } else {
            view.setBackgroundResource(R.drawable.set_button_off);
        }
    }

    /**
     * 退出登录
     */
    void doLoginOut() {
        clearUserInfo(new String[]{
                PuTaoConstants.PREFERENCE_KEY_UID,
                PuTaoConstants.PREFERENCE_KEY_MOBILE,
                PuTaoConstants.PREFERENCE_KEY_NICKNAME,
                PuTaoConstants.PREFERENCE_KEY_TOKEN,
                PuTaoConstants.PREFERENCE_KEY_PASSWORD});
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_BABY_ID, PuTaoConstants.DEVAULT_BABY_ID);
        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_LOGIN_OUT));
        ActivityHelper.startActivity(mActivity, ActivityLoginRegister.class);
        mActivity.finish();
    }

    void clearUserInfo(String[] keys) {
        if (keys == null || keys.length == 0)
            return;
        for (int i = 0; i < keys.length; i++) {
            SharedPreferencesHelper.saveStringValue(mContext, keys[i], "");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.btn_set_using_only_wifi:
                mBoolWifiOnly = !mBoolWifiOnly;
                SharedPreferencesHelper.saveBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_UP_DOWN_ONLY_WIFI, mBoolWifiOnly);
                updateOnOffBtnBackground(btn_set_using_only_wifi, mBoolWifiOnly);
                break;
            case R.id.btn_set_backround_upload:
                mBoolBackUpload = !mBoolBackUpload;
                SharedPreferencesHelper.saveBooleanValue(mContext, PuTaoConstants.PREFERENCE_KEY_COUNTINUTE_UPLOAD_BACKGROUND, mBoolBackUpload);
                updateOnOffBtnBackground(btn_set_backround_upload, mBoolBackUpload);
                break;
            case R.id.set_layout_baby_manager:
                ActivityHelper.startActivity(mActivity, ActivityChildManager.class);
                break;
            case R.id.set_layout_account_security:
                break;
            case R.id.set_layout_lockpwd_set:
                break;
            case R.id.set_layout_about_us:
                ActivityHelper.startActivity(this, ActivityAboutUs.class);
                break;
            case R.id.set_layout_opinion_feedback:
                ActivityHelper.startActivity(this, ActivityFeedback.class);
                break;
            case R.id.set_layout_login_out:
                doLoginOut();
                break;
            case R.id.set_layout_clear_cache:
                AppHelper.clearAlbumDiskCache();
                showToast("清除成功");
                break;
            case R.id.set_layout_user_icon:
                showSeLectDialog();
                break;
            case R.id.set_layout_shareto_friend:
                showShareAppDialog();
                break;
        }
    }

    /**
     * 弹出分享APP框
     */
    void showShareAppDialog() {

        Dialog dialog = new DialogBuilderFactory<ShareAppDialogBuilder>(mContext, DialogBuilderFactory.DialogType.SHAREAPP).Builder().setOnShareAppChannelListener(new ShareAppDialogBuilder.onShareAppChannelListener() {
            @Override
            public void onShare(Dialog dialog, ShareAppDialogBuilder.ShareAppChannel channel) {
                if (channel != null) {
                    String shareText = "推荐您下载一个叫“葡萄时光”的应用，除了能自动帮你把宝宝的照片生成漂亮的成长时光轴，还能实现最私密的家庭间照片共享，点击链接马上下载:" + PuTaoConstants.QQ_INVITE_URL + ")";
                    switch (channel) {
                        case QQ:
                            shareText = "葡萄时光能把宝宝的照片生成漂亮的成长时光轴，实现家庭间照片共享，(下载地址:" + PuTaoConstants.QQ_INVITE_URL + ")";
                            mShareTools.doInviteByQQ(shareText);
                            break;
                        case SMS:
                            ActivityHelper.startSMSActivity(mActivity, shareText);
                            break;
                        case CHAT:
                            mShareTools.doInviteByWeiXin(shareText);
                            break;
                    }
                }
                dialog.dismiss();
            }
        }).Create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }


    void showSeLectDialog() {
        SelectDialogBuilder.DialogButtonOnClickListener mDialogListener = new SelectDialogBuilder.DialogButtonOnClickListener() {
            @Override
            public void positiveOnClick(Dialog dialog) {
                startCameraApp();
                dialog.dismiss();
            }

            @Override
            public void negativeOnClick(Dialog dialog) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("multiSelectState", false);
                ActivityHelper.startActivity(mActivity, ActivityAlbumPhotoSelect.class, bundle);
                dialog.dismiss();
            }
        };
        Dialog dialog = new DialogBuilderFactory<SelectDialogBuilder>(mContext, DialogBuilderFactory.DialogType.SELECT).Builder()
                .setDialogButtonOnClickListener(mDialogListener)
                .setNegativeButton("从相册选择照片").setPositiveButton("拍照").Create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void getUserAvatar() {

        HashMap<String, String> params = new HashMap<String, String>();

        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_USER_AVATAR,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                String avatar = json.getString("avatar");

                                DisplayImageOptions options = new DisplayImageOptions.Builder()
                                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                                        .cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565)
                                        .considerExifParams(true)
                                        .build();
                                ImageLoader.getInstance().displayImage(avatar, user_icon, options);
                            }
//                                String msg = json.getString("msg");
//                                showToast(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                    }
                });

    }


    private Uri mPhotoUri;
    private static final int REQUEST_CODE_PHOTO_SELECT = 2;
    private String photo_path;

    private void getUploadToken() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("type", "uploadBabyRpAvatar");
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_TOKEN, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)),
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        try {
                            JSONObject json = new JSONObject(response);
                            String status = json.getString("status");
                            if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                String uploadToken = json.getString("uploadToken");
                                uploadUserIcon(uploadToken);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                        showToast("保存图像失败!");
                    }
                });
    }

    private void uploadUserIcon(String token) {
        RequestParams params = new RequestParams(new HttpRequestUtil().buildHttpRequestParams(new HashMap()));
        params.put("uploadToken", token);
        try {
            File file = new File(photo_path);
            if (file.exists()) {
                params.put("file", file);
            } else {
                Loger.d("无图像文件!");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Loger.d("chen++++uploadUserIcon():"+photo_path);
        HttpRequestUtil.doFileUploadRequest(mContext, PuTaoConstants.API_UPLOAD_UPLOAD_UPLOAD, params, new HttpRequestUtil.FileUploadRequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                //{"avatar":"http:\/\/file.cloud.dev.putao.io\/f\/45\/f45d16f4ae86cec5640a5f2c430defb157aabc96.jpg","status":200}
                try {
                    JSONObject json = new JSONObject(response);
                    String status = json.getString("status");

                    //解析返结果data中的参数
                    String msg = json.getString("msg");
                    if (status.equals(HttpRequestUtil.ResponseCode.api_code_200)) {

                        String avatar = json.getString("avatar");
                        DisplayImageOptions options = new DisplayImageOptions.Builder()
                                .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                                .cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565)
                                .considerExifParams(true)
                                .build();
                        ImageLoader.getInstance().displayImage(avatar, user_icon, options);
                    }
                    showToast(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.i("response:" + response);
            }

            @Override
            public void onprogress(int bytesWritten, int totalSize) {
            }
        });
    }

    private void startCameraApp() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            ContentValues contentValues = new ContentValues(2);
            contentValues.put(MediaStore.Images.Media.DATA, CommonUtils.getOutputMediaFile().getPath());
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
            startActivityForResult(intent, REQUEST_CODE_PHOTO_SELECT);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PHOTO_SELECT && resultCode == RESULT_OK) {
            Uri uri = null;
            if (data != null && data.getData() != null) {
                uri = data.getData();
            }
            if (uri == null) {
                if (mPhotoUri != null) {
                    uri = mPhotoUri;
                }
            }
            try {
                String[] projection = {MediaStore.MediaColumns._ID, MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(uri, projection, null, null, null);
                c.moveToFirst();
                String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                File file = new File(photoFileName);
                File destDir = CommonUtils.getOutputMediaDir();
                file.renameTo(destDir);
                photo_path = destDir.getPath() + File.separator + file.getName();
                final String[] SCAN_TYPES = {"image/jpeg"};
                MediaScannerConnection.scanFile(mContext, new String[]{photo_path}, SCAN_TYPES, null);

                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                        .cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
                        .considerExifParams(true)
                        .build();
                ImageLoader.getInstance().displayImage("file://" + photo_path, user_icon, options);

                Bundle bundle = new Bundle();
                bundle.putString("photo_path", photo_path);
                ActivityHelper.startActivity(mActivity, ActivityCropImage.class, bundle);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (mPhotoUri != null) {
                getContentResolver().delete(mPhotoUri, null, null);
            }
        }
    }
}
